<template>
    <div class="center-map">
        <div class="china-map-box">
            <div class="tab-list">
                <div v-for="(item, i) in list" :class="[currentIndex == i ? 'active' : '']" class="tab" @click="changeTab(item, i)">
                    {{ item.name }}
                </div>
            </div>
            <div v-show="currentIndex == list.length - 1" class="route-navigation">
                <a-form :model="formState" layout="inline">
                    <a-form-item class="form-item-self" label="起点">
                        <a-input v-model:value="formState.start" placeholder="请输入起点"></a-input>
                    </a-form-item>
                    <a-form-item class="form-item-self" label="终点">
                        <a-input v-model:value="formState.end" placeholder="请输入终点"></a-input>
                    </a-form-item>
                    <a-form-item>
                        <a-button class="reset-btn" @click="removeInput">清空</a-button>
                        <a-button class="search-btn" @click="searchRoute" :loading="searchFlag" :disabled="searchFlag"> 路线规划 </a-button>
                    </a-form-item>
                </a-form>
                <div v-show="showRoutePanel" v-click-outside="outClick" class="line-container">
                    <div v-show="routeList.length" class="has-data">
                        <div class="line-title"> {{ panelTitle }}</div>
                        <div class="line-content">
                            <div class="start">起点</div>
                            <div class="line-body">
                                <div class="line"></div>
                                <div class="line-desc">
                                    <p v-for="(item, i) in routeList" :key="i">{{ item }}</p>
                                </div>
                            </div>
                            <div class="end">终点</div>
                        </div>
                    </div>
                    <div v-show="!routeList.length" class="empty-data"> 暂无数据</div>
                </div>
            </div>
            <div v-show="showHospitalList" class="reset-map" @click="resetMap">
                <RedoOutlined title="重置地图" />
            </div>
            <RoutePanel
                class="driving-route-panel"
                v-show="showDrivingPanel"
                :drivingRoute="drivingRoute"
                :drivingTitle="drivingTitle"
                @out-click="showDrivingPanel = false"
            />
            <div style="flex: 1; overflow: hidden; margin: 0 0 10px">
                <div id="mapContainer" class="mapContainer"></div>
            </div>
            <div v-show="false" id="container"></div>
            <div v-show="false" id="panel"></div>
            <div class="map-legend">
                <div v-for="(item, i) in legendList" :key="i" class="legend-item">
                    <div><img :src="item.img" alt="" class="legend-img" /> {{ item.text }}</div>
                </div>
            </div>
            <!--            <div class="level">地图层级：{{ level }}</div>-->
        </div>
        <div class="center-footer" v-if="showFooter">
            <div class="count-item">
                <div class="num">{{ useDetail?.alerdyreceive || '0' }}</div>
                <div class="text">累计受理</div>
            </div>
            <div class="count-item">
                <div class="num">{{ useDetail?.totalacceptance || '0' }}</div>
                <div class="text">累计处置</div>
            </div>
        </div>
        <!-- 附近医院、医疗点  -->
        <div class="hospital-list" v-if="showHospitalList">
            <div class="hospital-item" v-for="(item, index) in hospitalList" :key="index" @click="showDrivingLine(item)">
                <div>{{ item.name }}</div>
                <div>相距{{ item.distance }}</div>
                <div>驾车大约{{ item.driveTime }}</div>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
    import { nextTick, onMounted, ref } from 'vue';
    import { message } from 'ant-design-vue';
    import { RedoOutlined } from '@ant-design/icons-vue';
    import { Map } from '/@/assets/mapUtils/map';
    import { aircraft, getKmStr, getTimeStr, legendList, mapApiSwitch, tabList, TabType } from '/@/components/chinaMap/chinaHooks';
    import { useDetailStore } from '/@/store/modules/detailData.ts';
    import RoutePanel from '/@/components/chinaMap/components/routePanel.vue';
    import { mapData } from '/@/views/yinChuanTest/mockData.ts';

    const props = defineProps({
        //是否展示底部统计
        showFooter: {
            type: Boolean,
            default: () => {
                return true;
            },
        },
        //地图是否按照接口数据的中心点定位
        computedCenter: {
            type: Boolean,
            default: () => {
                return true;
            },
        },
        // 地图配置
        mapOptions: {
            type: Object,
            default: () => {
                return {};
            },
        },
        //是否展示最近的三个医院
        showHospitalList: {
            type: Boolean,
            default: () => {
                return false;
            },
        },
        hospitalList: {
            type: Array,
            default: () => {
                return [];
            },
        },
    });
    const emits = defineEmits(['clearHospitalList']);
    const useDetail = useDetailStore();
    const formState = ref({
        start: '',
        end: '',
    });
    const list = ref(tabList);
    const currentIndex = ref(0);

    function changeTab(item, i: number) {
        currentIndex.value = i; // 地方医院
        Map.clearActiveHospital();
        closeDrivingElement();
        Map.map.off('moveend', logMapinfo);
        if (TabType.diFangYiYuan == item.type) {
            Map.removeOverlayGroup();
            Map.map.on('moveend', logMapinfo);
            return;
        }
        if (TabType.zhiShengJi == item.type) {
            Map.createAircraft(aircraft);
            return;
        } else {
            getMapData(item.type, { type: item.type });
        }
    }

    const currentCityCode = ref('');

    function logMapinfo() {
        Map.map.getCity(function (info) {
            const { citycode } = info;
            if (currentCityCode.value != citycode) {
                Map.createActiveHospital(citycode);
                currentCityCode.value = citycode;
            }
        });
    }

    const level = ref(0);

    function setLevel() {
        //获取当前地图级别
        level.value = Map.map.getZoom();
    }

    async function getMapData(type, params = {}) {
        try {
            const { code, result } = mapData;
            if (code == 200) {
                if (Array.isArray(result) && result.length > 0) {
                    Map.createOverlay(
                        result,
                        {
                            content: (val) => {
                                return `<div style="
                                width: 21px;
                                height: 44px;
                                position: absolute;
                                left: -20px;
                                top: -20px;" title="${val?.name}">
                            </div>`;
                            },
                        },
                        () => {},
                        props.computedCenter
                    );
                } else {
                    Map.removeOverlayGroup();
                }
            }
        } catch (e) {
            console.warn(e);
        }
    }

    onMounted(() => {
        Map.initMap({ el: 'mapContainer', option: props.mapOptions }).then(() => {
            getMapData(tabList[0].type);
            Map.map && Map.map.on('zoomend', setLevel);
            Map.map && Map.map.on('zoomend', setLevel);
        });
    });
    const routeList = ref([]);
    const showRoutePanel = ref(false);
    const panelTitle = ref();

    function outClick() {
        showRoutePanel.value = false;
    }

    function setTitle({ time, distance }) {
        let str = '全程';
        str += getTimeStr(time);
        str += getKmStr(distance);
        panelTitle.value = str;
    }

    let searchFlag = ref(false);

    /**
     * @desc 路线规划
     * @param callback
     */
    function searchRoute(callback: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null) {
        showRoutePanel.value = false;
        panelTitle.value = '';
        if (!formState.value.start) {
            return message.warn('请输入起点');
        }
        if (!formState.value.end) {
            return message.warn('请输入终点');
        }
        searchFlag.value = true;
        //基本地图加载
        let map = new AMap.Map('container', {
            resizeEnable: true,
            center: [116.397428, 39.90923], //地图中心点
            zoom: 13, //地图显示的缩放级别
        });
        //构造路线导航类
        let driving = new AMap.Driving({
            map: map,
            panel: 'panel',
        });
        // 根据起终点名称规划驾车导航路线
        driving.search([{ keyword: formState.value.start }, { keyword: formState.value.end }], function (status, result) {
            // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            if (status === 'complete') {
                searchFlag.value = false;

                //  console.log('绘制驾车路线完成');
            } else {
                searchFlag.value = false;

                //  console.log('获取驾车数据失败：' + result);
            }
        });
        AMap.Event.addListener(driving, 'complete', (res) => {
            const data = JSON.parse(JSON.stringify(res));
            searchFlag.value = false;
            if (data.info == 'OK') {
                const { routes } = data;
                setTitle(routes[0]);
                let arr = [];
                arr.push(data.originName);
                routes[0].steps.map((item: any) => {
                    arr.push(item.instruction);
                });
                arr.push(data.destinationName);
                showRoutePanel.value = true;
                routeList.value = arr;
            }
        });
    }

    function removeInput() {
        formState.value.start = '';
        formState.value.end = '';
        searchFlag.value = false;
    }

    // 驾车路线
    const drivingRoute = ref([]);
    const drivingTitle = ref('');
    const showDrivingPanel = ref(false);

    function showDrivingLine(item) {
        nextTick(() => {
            drivingTitle.value = '全程' + item.driveTime + item.distance;
            drivingRoute.value = item.routeList?.map((item) => item?.instruction);
            showDrivingPanel.value = true;
            if (item.lon) {
                Map.clearNaviLine();
                Map.createNaviLine(item.userLocation, [item.lon, item.lat]);
            }
        });
    }

    function closeDrivingElement() {
        Map.clearNavigationElements();
        formState.value.start = '';
        formState.value.end = '';
        showDrivingPanel.value = false;
        emits('clearHospitalList');
    }

    function resetMap() {
        closeDrivingElement();
        changeTab(list.value[currentIndex.value], currentIndex.value);
    }
</script>
<style lang="less" scoped>
    .center-map {
        flex: 1;
        color: #fff;
        display: flex;
        flex-direction: column;
        align-content: space-between;

        .china-map-box {
            flex: 1;
            display: flex;
            flex-direction: column;
            position: relative;
        }

        .tab-list {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            font-size: 16px;

            .tab {
                width: calc(100% / 8);
                height: 40px;
                display: flex;
                justify-content: center;
                align-items: center;
                color: #29f1fa;
                background: url('/@/assets/img/tab-default.png') no-repeat;
                background-size: 100% 100%;
                cursor: pointer;
                transition: all 0.3s;

                &.active {
                    color: #fff;
                    background: url('/@/assets/img/tab-active.png') no-repeat;
                    background-size: 100% 100%;
                }
            }
        }

        .route-navigation {
            margin: 12px 0;
            width: 100%;
            height: 46px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #002e64;
            border-radius: 6px;
            position: absolute;
            top: 36px;
            z-index: 999;
            transition: all 0.3s;

            :deep(.form-item-self) {
                label {
                    color: #29f1fa;
                }

                .ant-input {
                    width: 280px;
                    color: #d6d9e0;
                    background: #2a4164;
                    border-radius: 2px 2px 2px 2px;
                    border: 1px solid #1b7ef2;
                }
            }

            .reset-btn {
                width: 64px;
                height: 32px;
                border-radius: 5px;
                color: #45a2ff;
                background: #002e64;
                border: 1px solid #45a2ff;
            }

            .search-btn {
                margin-left: 10px;
                width: 120px;
                height: 32px;
                color: #efefef;
                background: #45a2ff;
                border-radius: 5px;
                border-color: #45a2ff;
            }

            .line-container {
                position: absolute;
                right: 0;
                top: 54px;
                width: 288px;
                padding: 9px 18px;
                min-height: 200px;
                max-height: 473px;
                overflow: auto;
                background: #2a4164;
                border-radius: 2px;
                border: 1px solid #1b7ef2;

                .line-title {
                    margin-bottom: 9px;
                    font-size: 14px;
                    font-weight: 700;
                    color: rgba(255, 255, 255, 0.8);
                }

                .line-content {
                    font-size: 12px;

                    .start {
                        display: flex;
                        align-items: center;

                        &::before {
                            content: '起';
                            color: #fff;
                            width: 20px;
                            height: 20px;
                            margin-right: 7px;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            border-radius: 50%;
                            background: #1478f5;
                        }
                    }

                    .end {
                        display: flex;
                        align-items: center;

                        &::before {
                            content: '终';
                            color: #fff;
                            width: 20px;
                            height: 20px;
                            margin-right: 7px;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            border-radius: 50%;
                            background: #1478f5;
                        }
                    }

                    .line-body {
                        display: flex;
                        //max-height: 370px;
                    }

                    .line {
                        width: 1px;
                        //max-height: 370px;
                        background-color: #1478f5;
                        margin: 5px 19px 5px 8px;
                    }

                    .line-desc {
                        flex: 1;
                    }
                }

                .empty-data {
                    margin-top: 30%;
                    text-align: center;
                }
            }
        }

        .reset-map {
            position: absolute;
            left: 0;
            top: 50px;
            z-index: 99;
            font-size: 20px;
            color: #05d5ff;
            cursor: pointer;
            background: #243b5d;
            padding: 0px 6px;
        }

        //驾驶路线导航面板
        .driving-route-panel {
            position: absolute;
            right: 0;
            top: 86px;
            width: 288px;
            padding: 9px 18px;
            min-height: 200px;
            max-height: 473px;
            overflow: auto;
            background: #2a4164;
            border-radius: 2px;
            border: 1px solid #1b7ef2;
            z-index: 99;
        }

        .mapContainer {
            flex: 1;
            height: calc(100% + 22px);
            margin: 10px 0;
        }

        .map-legend {
            position: absolute;
            bottom: 15px;
            left: 10px;
            width: 200px;
            display: flex;
            flex-wrap: wrap;

            .legend-item {
                width: 50%;
                font-size: 12px;
                font-weight: 400;
                line-height: 30px;

                .legend-img {
                    width: 20px;
                }
            }
        }

        .level {
            position: absolute;
            top: 50px;
            left: 400px;
            font-size: 18px;
            color: #fff;
        }

        .center-footer {
            display: flex;
            justify-content: center;
            margin-bottom: 10px;
            gap: 20px;

            .count-item {
                width: 340px;
                height: 80px;
                display: flex;
                color: #ffffff;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                background: #00071b;
                box-shadow: inset 0 0 40px 0 #1b7ef2;
                border-radius: 4px;

                .num {
                    font-size: 24px;
                    font-weight: 700;
                }

                .text {
                    font-size: 16px;
                    font-weight: 400;
                }
            }
        }

        .hospital-list {
            position: absolute;
            bottom: 200px;
            width: 800px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;

            .hospital-item {
                position: relative;
                flex: 1;
                gap: 20px;
                min-width: 230px;
                max-width: 230px;
                height: 110px;
                text-align: center;
                padding: 10px;
                margin: 0 10px;
                color: #fff;
                font-size: 16px;
                background-color: #00152b;
                border: 1px solid #1b7ef2;
                border-radius: 12px;
                box-shadow: 0 1px 11px 0 rgba(194, 189, 189, 0.5);
                cursor: pointer;
            }

            .hospital-item:hover {
                background-color: #192a46;
                box-shadow: inset 0px 0px 16px 3px #2562a9;
            }
        }
    }
</style>
